import React, { useState, useEffect } from 'react';
import planIcon from '@/assets/img/plan_icon.png';
import { Button, Modal, Form, Input, message } from 'antd';
import TRNotification from '#/utils/notification.js';
import { HttpCode } from '#/utils/contacts.js';
import type { IMaintenancePlanModalType, IDealElementOptions, IDataListType } from '../../../type';
import { titleMap } from '../../../dictionary';
import { ShowDatePicker, ShowSelect } from '../index';
import styles from './index.less';
import moment from 'moment';

const TextArea = Input.TextArea;
interface IProps {
  /**
   * 是否是编辑状态
   */
  maintenancePlanModalType: IMaintenancePlanModalType;
  /**
   * 所有交易单元
   */
  allStationData?: IDealElementOptions[];
  /**
   * 当前新建编辑计划数据
   */
  record?: IDataListType;
  /**
   * 查询交易单元装机容量
   */
  queryCapacityByStationId: (stationId: string) => number | undefined;
  /**
   * 保存
   */
  onSubmit?: (data: IDataListType) => any;
  onPress: (data: Record<string, any>) => void;
}

const MaintenanceScheduleModalComponent = (props: IProps) => {
  const {
    maintenancePlanModalType,
    allStationData = [],
    record,
    onSubmit,
    queryCapacityByStationId,
    onPress,
  } = props;
  const [visible, setVisible] = useState<boolean>(true);
  const [stationData, setStationData] = useState<IDealElementOptions[]>([]);
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [capacity, setCapacity] = useState<number>();
  const [form] = Form.useForm();

  useEffect(() => {
    if (record) {
      const data = {
        stationId: record?.stationId ? String(record?.stationId) : undefined,
        date:
          record?.startDate && record?.endDate && record?.startTime && record?.endTime
            ? [
                moment(`${record?.startDate} ${record?.startTime}`),
                moment(`${record?.endDate} ${record?.endTime}`),
              ]
            : undefined,
        effectCapacity: record?.effectCapacity ?? undefined,
        tendingEvent: record?.tendingEvent || '',
      };
      if (record?.stationId) {
        (async () => {
          const _capacity =
            queryCapacityByStationId &&
            (await queryCapacityByStationId(record?.stationId as string));
          setCapacity(_capacity);
        })();
      }
      form && form.setFieldsValue(data);
    }
  }, [record]);

  useEffect(() => {
    if (allStationData) {
      const result: any = allStationData.sort((a: any, b: any) => a.label.localeCompare(b.label));
      setStationData(result);
    }
  }, [allStationData]);

  // 改变交易单元
  const onChangeStationId = async (e: string) => {
    const _capacity = queryCapacityByStationId && (await queryCapacityByStationId(e));
    setCapacity(_capacity);
    const value = form && form.getFieldsValue();
    let _value = value?.effectCapacity;
    if (_value) {
      _value =
        Number(_value) > Number(_capacity)
          ? Number(_capacity).toFixed(3)
          : Number(_value).toFixed(3);
      form &&
        form.setFieldsValue({
          ...value,
          effectCapacity: _value,
        });
    }
  };

  // 编辑影响装机容量
  const onBlurEffectCapacity = (e: any) => {
    const value = form && form.getFieldsValue();
    let _value = e.target.value;
    if (_value) {
      _value =
        Number(_value) > Number(capacity) ? Number(capacity).toFixed(3) : Number(_value).toFixed(3);
      form &&
        form.setFieldsValue({
          ...value,
          effectCapacity: _value,
        });
    }
  };

  // 编辑检修日期
  const onChangeDate = (date: any) => {
    const arr = ['00', '15', '30', '45'];
    let _startDate = date[0];
    let _endDate = date[1];
    let _date = date;
    const _startTime = moment(date[0]).format('mm');
    const _endTime = moment(date[1]).format('mm');
    if (!arr.includes(_startTime)) {
      _startDate = moment(moment(date[0]).format('YYYY-MM-DD: HH:00'));
    }
    if (!arr.includes(_endTime)) {
      _endDate = moment(moment(date[1]).format('YYYY-MM-DD: HH:00'));
    }
    const _diffm = moment(moment().add(1, 'day').startOf('day')).diff(
      moment(_startDate),
      'minutes',
    );
    let _diffm1 = moment(_endDate).diff(moment(_startDate), 'minutes');
    if (_diffm === 0) {
      _startDate = moment(_startDate).add(15, 'minutes');
      _diffm1 = moment(_endDate).diff(moment(_startDate), 'minutes');
      if (_diffm1 <= 0) {
        _endDate = moment(_startDate).add(15, 'minutes');
      }
    } else {
      if (_diffm1 === 0) {
        _endDate = moment(_endDate).add(15, 'minutes');
      }
    }
    _date = [_startDate, _endDate];
    const value = form && form.getFieldsValue();
    form &&
      form.setFieldsValue({
        ...value,
        date: _date,
      });
  };

  //  取消按钮
  const _onCancel = () => {
    setVisible(false);
    onPress({ index: 0 });
  };

  // 表单提交
  const _onSubmit = () => {
    form &&
      form.validateFields().then(async (values) => {
        const startDiffEndtime = moment(values.date[1]).diff(moment(values.date[0]), 'minutes');
        let _startTime = moment(values.date[0]).format('HH:mm');
        let _endTime = moment(values.date[1]).format('HH:mm');
        if (startDiffEndtime < 0) {
          _startTime = moment(values.date[1]).format('HH:mm');
          _endTime = moment(values.date[0]).format('HH:mm');
        }
        const _startDate =
          _startTime === '00:00'
            ? moment(values.date[0]).subtract(1, 'day').format('YYYY-MM-DD')
            : moment(values.date[0]).format('YYYY-MM-DD');
        const _endDate =
          _endTime === '00:00'
            ? moment(values.date[1]).subtract(1, 'day').format('YYYY-MM-DD')
            : moment(values.date[1]).format('YYYY-MM-DD');
        const _data: IDataListType = {
          id: record?.id ?? null,
          stationId: values.stationId,
          stationName: allStationData.find((item) => item.value === values.stationId)?.label,
          startDate: _startDate,
          startTime: _startTime === '00:00' ? '24:00' : _startTime,
          endDate: _endDate,
          endTime: _endTime === '00:00' ? '24:00' : _endTime,
          effectCapacity: Number(Number(values.effectCapacity).toFixed(3)),
          tendingEvent: values?.tendingEvent || '',
        };
        if (onSubmit) {
          setIsLoading(true);
          const res = await onSubmit(_data);
          if (res && res?.statusCode === HttpCode.SUCCESS) {
            message.success('保存成功');
            setVisible(false);
            onPress({ index: 1 });
          } else {
            message.error(res.message || '系统异常');
          }
          setIsLoading(false);
        }
      });
  };

  const onChangeValue = (e: any) => {
    const value = form && form.getFieldsValue();
    const regValue = /^[0-9]*(\.[0-9]*)?$/;
    let _value = e?.target?.value;
    if (_value && !regValue.test(e?.target?.value)) {
      _value = '';
    }
    form &&
      form.setFieldsValue({
        ...value,
        effectCapacity: _value,
      });
  };

  const filterOption = (input: string, option: { value: any; label: any }) => {
    const { value, label } = option;
    return (
      value?.toLowerCase().indexOf(input.toLowerCase()) >= 0 ||
      label?.toLowerCase().indexOf(input.toLowerCase()) >= 0
    );
  };

  const disabledDate = (current: any) => {
    return current && current < moment().startOf('day');
  };

  const footerRender = () => [
    <Button key="dtest1" onClick={_onCancel} loading={isLoading}>
      取消
    </Button>,
    <Button key="dtest2" type="primary" onClick={_onSubmit} loading={isLoading}>
      确定
    </Button>,
  ];

  return (
    <Modal
      width={580}
      className={styles.modal}
      centered
      maskClosable={false}
      visible={visible}
      title={
        <div className={styles.titleDiv}>
          <img src={planIcon} className={styles.titleLogo} />
          <span className={styles.title}>{titleMap[maintenancePlanModalType].title}</span>
        </div>
      }
      onCancel={_onCancel}
      footer={footerRender()}
    >
      <div className={styles.container}>
        <Form
          className={styles.form}
          form={form}
          name="maintenanceSchedule"
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 18 }}
          colon={false}
          labelAlign="left"
          autoComplete="off"
          requiredMark={false}
        >
          <Form.Item
            name="stationId"
            label="交易单元"
            rules={[{ required: true, message: '请选择交易单元' }]}
          >
            <ShowSelect
              placeholder={'交易单元'}
              showArrow={true}
              options={stationData as any}
              showSearch={true}
              filterOption={filterOption as any}
              onChange={onChangeStationId}
              disabled={maintenancePlanModalType === 'edit'}
            />
          </Form.Item>
          <Form.Item
            label="计划时间段"
            name="date"
            rules={[{ required: true, message: '请选择计划时间段' }]}
          >
            <ShowDatePicker
              showTime
              placeholder={['开始时间', '结束时间']}
              format="YYYYMMDD HHmm"
              minuteStep={15}
              disabledDate={disabledDate}
              type="rangePicker"
              onChange={onChangeDate}
            />
          </Form.Item>
          <Form.Item
            name="effectCapacity"
            label="影响容量"
            rules={[{ required: true, message: '请填写影响容量' }]}
          >
            <Input
              placeholder="请填写"
              suffix="MW"
              onBlur={onBlurEffectCapacity}
              onChange={onChangeValue}
            />
          </Form.Item>
          <Form.Item
            name="tendingEvent"
            label="检修事件"
            rules={[{ max: 500, message: '检修事件不可超过500个字符' }]}
          >
            <TextArea maxLength={500} placeholder="请填写" />
          </Form.Item>
        </Form>
      </div>
    </Modal>
  );
};

class MaintenanceScheduleModal {
  __key__ = '';

  show = (props: any) => {
    return new Promise((resolve) => {
      if (this.__key__ !== '') return;
      this.__key__ = String(Date.now());
      TRNotification.add({
        key: this.__key__,
        content: (
          <MaintenanceScheduleModalComponent
            {...props}
            onPress={(result: any) => {
              TRNotification.remove(this.__key__);
              this.__key__ = '';
              resolve(result);
            }}
          />
        ),
        duration: null,
        dismiss: this.dismiss,
      });
    });
  };

  dismiss = () => {
    if (this.__key__.length > 0) {
      TRNotification.remove(this.__key__);
      this.__key__ = '';
    }
  };
}

export default new MaintenanceScheduleModal();
